//
// Created by mio on 25-5-16.
//

#ifndef AVPLAYER_H
#define AVPLAYER_H

#include <atomic>

#include "AudioRender.h"
#include "OpenGLRender.h"
#include "AVDEMuxer.h"

class EventLoop;
class SigConnection;

class AVPlayer : public OpenGLRender, public AudioRender
{
    Q_OBJECT

public:
    explicit AVPlayer(EventLoop* loop, QWidget* parent = nullptr);
    ~AVPlayer();
    bool Connect(QString ip, uint16_t port, QString code);

    void HandleStopStream();
    bool HandleStartStream(const QString& streamAddr);

signals:
    void sig_repaint(AVFramePtr frame);

protected:
    void AudioPlay();
    void VideoPlay();
    void Init();
    void Close();

    void resizeEvent(QResizeEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void keyReleaseEvent(QKeyEvent *event) override;

private:
    std::atomic_bool stop_ = false;
    EventLoop* loop_;
    AVContext* avContext_ = nullptr;
    std::shared_ptr<SigConnection> sig_conn_;
    std::unique_ptr<AVDEMuxer> avDEMuxer_ = nullptr;
    std::unique_ptr<std::thread> audioThread_ = nullptr;
    std::unique_ptr<std::thread> videoThread_ = nullptr;
};

#endif //AVPLAYER_H